package GUILayer;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import ModelLayer.Guest;
import ModelLayer.KeyWord;

import ModelLayer.Room;
import ControlLayer.PersonCtr;
import ControlLayer.PersonException;
import ControlLayer.RBDateCtr;
import ControlLayer.RoomCtr;

public class RoomGUI extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	private RoomTypeModelGUI roomTypeModelGUI;
	private JTable table;
	private JTable guestTable;
	private DefaultTableModel tableModel;
	private DefaultTableModel guestTableModel;
	private JScrollPane tableScrollPane;
	private JScrollPane guestTableScrollPane;
	private JPanel tablePanel;
	private JPanel guestTablePanel;

	private JTextField textField_id;
	private JTextField textField_name;
	private JTextField textField_status;
	private JTextField textField_date;
	private JTextField textField_rtId;
	private JTextField textField_search;

	private JComboBox<String> status;
	private String[] listStrings = { KeyWord.Occupied.toString(),
			KeyWord.Available.toString(), KeyWord.ToClean.toString() };
	private RoomCtr roomCtr;
	private PersonCtr personCtr;
	private RBDateCtr rbDateCtr;

	public RoomGUI(JPanel panel) {
		rbDateCtr = new RBDateCtr();
		roomCtr = new RoomCtr();
		personCtr = new PersonCtr();
		roomTypeModelGUI = (RoomTypeModelGUI) panel;
		initialize();
	}

	public void initialize() {
		this.setLayout(new BorderLayout());
		TitledBorder title = BorderFactory.createTitledBorder("Room");
		title.setTitleJustification(TitledBorder.CENTER);
		this.setBorder(title);

		JPanel roomTablePanel = new JPanel();
		JPanel roomPanel = new JPanel();
		roomPanel.setLayout(new BoxLayout(roomPanel, BoxLayout.Y_AXIS));
		this.add(roomTablePanel, BorderLayout.CENTER);
		this.add(roomPanel, BorderLayout.EAST);

		roomTablePanel.setLayout(new BorderLayout());
		JPanel searchPanel = new JPanel();

		textField_search = new JTextField();
		textField_search.setColumns(50);
		searchPanel.add(textField_search);

		textField_search.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				showAllRooms();
			}
		});

		roomTablePanel.add(searchPanel, BorderLayout.NORTH);

		tablePanel = new JPanel();
		roomTablePanel.add(tablePanel, BorderLayout.CENTER);

		addRoomTable();
		showAllRooms();

		JLabel lblId = new JLabel("Id: ");
		JLabel lblname = new JLabel("Name: ");
		JLabel lblstatus = new JLabel("Status: ");
		JLabel lbldate = new JLabel("CheckOutDate(dd/mm/yyyy): ");
		JLabel lblrtId = new JLabel("RoomTypeId: ");

		textField_id = new JTextField();
		textField_name = new JTextField();
		textField_status = new JTextField();
		textField_date = new JTextField();
		textField_rtId = new JTextField();
		textField_id.setColumns(24);
		textField_name.setColumns(24);
		textField_status.setColumns(24);
		textField_date.setColumns(24);
		textField_rtId.setColumns(24);

		textField_id.setEditable(false);

		status = new JComboBox<String>(listStrings);
		status.setSelectedIndex(1);
		status.addActionListener(this);

		JPanel roomInfoPanel = new JPanel();
		roomPanel.add(roomInfoPanel);

		GroupLayout gl = new GroupLayout(roomInfoPanel);
		roomInfoPanel.setLayout(gl);
		roomInfoPanel.setBorder(BorderFactory.createTitledBorder("Room Info"));
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblId).addComponent(lblname)
								.addComponent(lblstatus).addComponent(lbldate)
								.addComponent(lblrtId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_id)
								.addComponent(textField_name)
								.addComponent(status)
								.addComponent(textField_date)
								.addComponent(textField_rtId)));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblId).addComponent(textField_id))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblname)
								.addComponent(textField_name))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblstatus).addComponent(status))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbldate)
								.addComponent(textField_date))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblrtId)
								.addComponent(textField_rtId)));

		guestTablePanel = new JPanel();
		guestTablePanel.setLayout(new BoxLayout(guestTablePanel,
				BoxLayout.Y_AXIS));
		roomPanel.add(guestTablePanel);
		addGuestTable();

		JPanel choicePanel = new JPanel();
		roomPanel.add(choicePanel);

		choicePanel.setLayout(new FlowLayout());

		JButton btnCreate = new JButton("Create");

		JButton btnSave = new JButton("Save");
		JButton btnDelete = new JButton("Delete");
		JButton btnClear = new JButton("Clear");

		choicePanel.add(btnCreate);

		choicePanel.add(btnSave);
		choicePanel.add(btnDelete);
		choicePanel.add(btnClear);

		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!textField_id.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null,
							"Please clear the fields before creating room",
							"Error", JOptionPane.ERROR_MESSAGE);
				} else {
					try {
						// insert room in room table
						roomCtr.insertRoom(textField_name.getText(),
								Integer.parseInt(textField_rtId.getText()),
								listStrings[status.getSelectedIndex()]);
						// increment nr of available rooms in RBDate
						rbDateCtr.incrementNrOfAvaiRoomForRT(
								Integer.parseInt(textField_rtId.getText()), 1);
						JOptionPane.showMessageDialog(null,
								"The room is created", "Create Room",
								JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception ex) {
						JOptionPane.showMessageDialog(null,
								"Please input correct values", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
					cleanTextField();
					showAllRooms();
					// TODO
					Date date = roomTypeModelGUI.getRtLeftPanel().getDate();

					roomTypeModelGUI.getRtLeftPanel().addTable(date);
				}
			}
		});

		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField_id.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null, "Please select a room",
							"Error", JOptionPane.ERROR_MESSAGE);
				} else {
					int reply = JOptionPane.showConfirmDialog(null,
							"Do you want to delete this room ?", "Delete Room",
							JOptionPane.YES_NO_OPTION,
							JOptionPane.WARNING_MESSAGE);
					if (reply == JOptionPane.YES_OPTION) {
						try {
							roomCtr.deleteRoom(Integer.parseInt(textField_id
									.getText()));
							// decrement nr of available room for roomtype
							rbDateCtr.decrementNrOfAvaiRoomForRT(
									Integer.parseInt(textField_rtId.getText()),
									1);
							JOptionPane.showMessageDialog(null,
									"The room is deleted", "Delete Room",
									JOptionPane.INFORMATION_MESSAGE);
							showAllRooms();
							Date date = roomTypeModelGUI.getRtLeftPanel()
									.getDate();

							roomTypeModelGUI.getRtLeftPanel().addTable(date);
							cleanTextField();
						} catch (Exception e1) {
						}
					}
				}
			}
		});

		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField_id.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null, "Please select a room",
							"Error", JOptionPane.ERROR_MESSAGE);
				} else {
					try {
						roomCtr.updateRoom(Integer.parseInt(textField_id
								.getText()), textField_name.getText(),
								new SimpleDateFormat("dd/MM/yyyy")
										.parse(textField_date.getText()),
								Integer.parseInt(textField_rtId.getText()),
								listStrings[status.getSelectedIndex()]);

						JOptionPane.showMessageDialog(null,
								"The room info is saved", "Save Room",
								JOptionPane.INFORMATION_MESSAGE);
						cleanTextField();
						showAllRooms();
					} catch (Exception a) {
						JOptionPane.showMessageDialog(null,
								"Please input correct values", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
					showAllRooms();
				}
			}
		});

		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cleanTextField();
			}
		});

		// add guest table
		// guestTablePanel = new JPanel();
		// guestTablePanel.setLayout(new BoxLayout(guestTablePanel,
		// BoxLayout.Y_AXIS));
		// roomPanel.add(guestTablePanel);
		// addGuestTable();
	}

	public void addGuestTable() {
		guestTableModel = new DefaultTableModel();
		guestTableModel.addColumn("GuestId");
		guestTableModel.addColumn("First Name");
		guestTableModel.addColumn("Last Name");

		guestTableScrollPane = new JScrollPane();
		guestTable = new JTable(guestTableModel);
		guestTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		guestTable.setAutoCreateRowSorter(true);
		guestTable.setPreferredScrollableViewportSize(new Dimension(20, 50));

		guestTablePanel.add(guestTableScrollPane);
		guestTableScrollPane.setViewportView(guestTable);
	}

	public void addRoomTable() {
		tableModel = new DefaultTableModel() {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		tableModel.addColumn("Id");
		tableModel.addColumn("Name");
		tableModel.addColumn("Status");
		tableModel.addColumn("CheckOutDate");

		tableScrollPane = new JScrollPane();

		table = new JTable(tableModel);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		table.setAutoCreateRowSorter(true);
		table.setPreferredScrollableViewportSize(new Dimension(400, 192));

		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int row = table.rowAtPoint(e.getPoint());
				if (e.getClickCount() == 1) {
					guestTableModel.setRowCount(0);
					if (showRoom(Integer.valueOf((Integer) table.getValueAt(
							row, 0)))) {
					}
				}
			}
		});
		tablePanel.add(tableScrollPane);
		tableScrollPane.setViewportView(table);

	}

	public void showRoomGuests(Room room) {
		guestTableModel.setRowCount(0);
		ArrayList<Guest> guests = room.getGuests();

		ArrayList<Guest> guests2 = new ArrayList<Guest>();
		for (Guest guest : guests) {
			try {
				guests2.add(personCtr.getGuestPersonWithoutAssociation(guest
						.getID()));
			} catch (PersonException e) {

			}
		}
		for (Guest guest : guests2) {
			guestTableModel.addRow(new Object[] { guest.getID(),
					guest.getfName(), guest.getlName() });
		}
	}

	public void showAllRooms() {
		String searchFilter = textField_search.getText();
		LinkedList<Room> rooms = roomCtr.getRoomsForRT(roomTypeModelGUI.getRt()
				.getId());
		tableModel.setRowCount(0);
		for (Room room : rooms) {
			if (((Integer) room.getId()).toString().toLowerCase()
					.contains(searchFilter.toLowerCase())
					|| room.getName().toLowerCase()
							.contains(searchFilter.toLowerCase())) {
				if (room.getEndDate() != null)
					tableModel
							.addRow(new Object[] {
									room.getId(),
									room.getName(),
									room.getStatus(),
									new SimpleDateFormat("dd/MM/yyyy")
											.format(room.getEndDate()),
									room.getRoomType().getId() });
				else
					tableModel.addRow(new Object[] { room.getId(),
							room.getName(), room.getStatus(), "",
							room.getRoomType().getId() });
			}
		}

	}

	public void cleanTextField() {
		guestTableModel.setRowCount(0);
		textField_date.setText("");
		textField_id.setText("");
		textField_name.setText("");
		textField_rtId.setText("");
		textField_status.setText("");
		status.setSelectedIndex(1);
	}

	public boolean showRoom(int roomId) {
		boolean success = true;
		try {
			Room room = roomCtr.getRoom(roomId);
			textField_id.setText(Integer.toString(room.getId()));
			textField_name.setText(room.getName());
			if (room.getEndDate() != null)
				textField_date.setText(new SimpleDateFormat("dd/MM/yyyy")
						.format(room.getEndDate()));
			textField_rtId
					.setText(Integer.toString(room.getRoomType().getId()));
			textField_status.setText(room.getStatus().toString());
			setStatus(room.getStatus());
			if (room.getGuests().size() != 0) {
				showRoomGuests(room);
			}
		} catch (Exception e) {
			success = false;
			JOptionPane.showMessageDialog(null, e, "Error",
					JOptionPane.ERROR_MESSAGE);
			return success;
		}
		return success;
	}

	public void setStatus(KeyWord s) {
		for (int i = 0; i < listStrings.length; i++) {
			if (s.toString().equals(listStrings[i]))
				status.setSelectedIndex(i);
		}
	}

	public RoomTypeModelGUI getRoomTypeModelGUI() {
		return roomTypeModelGUI;
	}

	public void setRoomTypeModelGUI(RoomTypeModelGUI roomTypeModelGUI) {
		this.roomTypeModelGUI = roomTypeModelGUI;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
	}

}
